<template>
  <a-drawer
    :visible="visible"
    :width="600"
    :body-style="{
      padding: '10px 20px 60px 20px',
      height: 'calc(100% - 65px)',
    }"
    @close="onSubmit"
  >
    <template #title>
      <span v-if="isStartOrEnd">
        {{ process.data.name }}
      </span>
      <template v-else-if="process.data">
        <a-input v-model:value="process.data.name" style="width: 200px" />
      </template>
    </template>
    <section class="content beauty-scroller-bar" v-if="process.data">
      <section class="module" v-if="process.type == 'approval'">
        <div class="text-title">审批类型</div>
        <a-radio-group
          v-model:value="process.data.approvalType"
          :options="common.approvalType"
        />
      </section>
      <section class="module">
        <div class="text-title">
          {{ isStartOrEnd ? "审批" : process.typeTxt }}人设置
        </div>
        <a-alert
          v-if="process.type == 'deal'"
          show-icon
          style="margin-bottom: 10px"
          message="当流程中某个节点不需要审批，但需要对审批单进行业务办理时，可设置办理人节点，场景如财务打款、处理盖章等"
        />
        <a-radio-group
          v-model:value="settingType"
          class="w-100p"
          button-style="solid"
        >
          <a-radio-button :value="1" class="w-50p text-center">
            设置{{ isStartOrEnd ? "审批" : process.typeTxt }}人
          </a-radio-button>
          <a-radio-button :value="2" class="w-50p text-center">
            表单设置
          </a-radio-button>
        </a-radio-group>
        <div class="mt-10">
          <template v-if="settingType == 1">
            <template v-if="process.type == 'approval'">
              <div
                class="mb-10"
                v-for="item of process.data.approver"
                :key="item.key"
              >
                <MemberSetting
                  title="审批人"
                  type="approval"
                  :content="item"
                  @remove="removeHandlerItem"
                />
              </div>
              <a-button type="link" @click="addHandlerItem('approval')">
                <template #icon>
                  <PlusOutlined />
                </template>
                添加审批人
              </a-button>
              <section class="module mt-10">
                <div class="text-title2">多人审批时采用的审批方式</div>
                <a-radio-group
                  v-model:value="process.data.approvalWay"
                  :options="common.approvalWay"
                />
              </section>
              <section class="module mt-10 user-tag">
                <div class="text-title2">审批人为空时</div>
                <a-radio-group
                  v-model:value="process.data.approverEmpty"
                  :options="common.approverEmpty"
                />
                <div v-if="process.data.approverEmpty == 2" class="mt-10">
                  <a-button
                    type="link"
                    @click="chooseMemberVisible = true"
                    class="mr-10"
                  >
                    <template #icon>
                      <PlusOutlined />
                    </template>
                    添加指定人员
                  </a-button>
                  <a-tag
                    closable
                    v-for="(user, index) of showMemberList"
                    :key="user.uid"
                    @close="memberRemove(index)"
                    style="margin: 5px 10px 5px 0"
                  >
                    <a-avatar
                      :src="user.avatar"
                      style="color: #fff; background-color: #2681f3"
                    >
                      <template #icon><UserOutlined /></template>
                    </a-avatar>
                    <span class="ml-10"> {{ user.realname }} </span>
                  </a-tag>
                </div>
                <div v-if="process.data.approverEmpty == 3" class="mt-10">
                  <a-select
                    style="width: 300px"
                    v-model:value="process.data.emptyAdmin"
                    :options="$store.getters.approvalBasicInfo.adminUserList"
                  />
                </div>
              </section>
              <section class="module mt-10">
                <div class="text-title2">审批人与提交人为同一人时</div>
                <a-radio-group v-model:value="process.data.selfApprove">
                  <a-radio
                    :style="radioStyle"
                    v-for="item of common.selfApprove"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-radio>
                </a-radio-group>
              </section>
              <section class="module">
                <div class="text-title2">提示</div>
                <a-badge
                  status="processing"
                  text="若审批人离职，会自动转交给审批人的上级代为处理"
                />
              </section>
              <a-divider style="margin: 20px 0px 10px 0px" />
            </template>
            <template v-if="process.type == 'deal'">
              <div
                class="mb-10"
                v-for="item of process.data.dealer"
                :key="item.key"
              >
                <MemberSetting
                  title="办理人"
                  type="deal"
                  :content="item"
                  @remove="removeHandlerItem"
                />
              </div>
              <a-button type="link" @click="addHandlerItem('deal')">
                <template #icon>
                  <PlusOutlined />
                </template>
                添加办理人
              </a-button>
              <section class="module mt-10 user-tag">
                <div class="text-title2">办理人为空时</div>
                <a-radio-group
                  v-model:value="process.data.dealerEmpty"
                  :options="common.dealerEmpty"
                />
                <div v-if="process.data.dealerEmpty == 2" class="mt-10">
                  <a-button
                    type="link"
                    @click="chooseMemberVisible = true"
                    class="mr-10"
                  >
                    <template #icon>
                      <PlusOutlined />
                    </template>
                    添加指定人员
                  </a-button>
                  <a-tag
                    closable
                    v-for="(user, index) of showMemberList"
                    :key="user.uid"
                    @close="memberRemove(index)"
                    style="margin: 5px 10px 5px 0"
                  >
                    <a-avatar
                      :src="user.avatar"
                      style="color: #fff; background-color: #2681f3"
                    >
                      <template #icon><UserOutlined /></template>
                    </a-avatar>
                    <span class="ml-10"> {{ user.realname }} </span>
                  </a-tag>
                </div>
                <div v-if="process.data.dealerEmpty == 3" class="mt-10">
                  <a-select
                    style="width: 300px"
                    v-model:value="process.data.emptyAdmin"
                    :options="$store.getters.approvalBasicInfo.adminUserList"
                  />
                </div>
              </section>
            </template>
            <section class="module" v-if="process.data.ccList">
              <div class="text-title" v-if="process.type != 'copy'">
                抄送人设置
              </div>
              <div
                class="mt-10"
                v-for="item of process.data.ccList"
                :key="item.key"
              >
                <MemberSetting
                  title="抄送人"
                  type="copy"
                  :content="item"
                  @remove="removeHandlerItem"
                />
              </div>
              <div class="mt-10">
                <a-button type="link" @click="addHandlerItem('copy')">
                  <template #icon>
                    <PlusOutlined />
                  </template>
                  添加抄送人
                </a-button>
              </div>
              <section class="module">
                <div class="text-title2">提示</div>
                <a-badge
                  status="processing"
                  text="抄送的人数最多支持100人以内"
                />
              </section>
            </section>
          </template>
          <template v-if="settingType == 2">
            <a-table
              :dataSource="controlList"
              :columns="formColumns"
              :pagination="false"
              size="small"
              rowKey="key"
            >
              <template #headerCell="{ column }">
                <template v-if="column.key === 'readCol'">
                  <a-checkbox v-model:checked="readAll" @change="readAllChange">
                    可读
                  </a-checkbox>
                </template>
              </template>

              <template #bodyCell="{ text, record, column }">
                <template v-if="column.key === 'readCol'">
                  <a-checkbox
                    v-model:checked="record.read"
                    @change="readChange(text)"
                  ></a-checkbox>
                </template>
              </template>
            </a-table>
          </template>
        </div>
      </section>
    </section>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onClose">取消</a-button>
        <a-button type="primary" @click.prevent="onSubmit"> 保存 </a-button>
      </a-space>
    </div>

    <!-- 选择人员 -->
    <ChooseOrgMember
      @request="$utils.commonRequest"
      :visible="chooseMemberVisible"
      :deptDisabled="true"
      :getDetail="true"
      :checkedList="memberCheckedList"
      @close="chooseMemberVisible = false"
      @success="handleChooseMemberSuccess"
    />
  </a-drawer>
</template>

<script>
import {
  defineComponent,
  watch,
  computed,
  reactive,
  toRefs,
  toRaw,
  ref,
} from "vue";
import { PlusOutlined, UserOutlined } from "@ant-design/icons-vue";
import store from "../../../../store";
import MemberSetting from "./MemberSetting.vue";
import common from "../js/common";
import { ChooseOrgMember } from "bl-common-vue3";
import { message } from "ant-design-vue";

export default defineComponent({
  name: "ProcessSetting",
  components: { MemberSetting, ChooseOrgMember, PlusOutlined, UserOutlined },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    content: {
      type: Object,
      default: () => ({}),
    },
    fromOther: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      // 流程内容
      process: {},
      //   设置类型 1 审批人、办理人设置 2表单设置
      settingType: 1,
      //   所有可读
      readAll: true,
      //   上一次的控件列表key
      lastControlKeys: [],
      // 控件列表
      controlList: [],
      // 选择指定人员
      chooseMemberVisible: false,
      memberCheckedList: {
        user: [],
        department: [],
      },
      showMemberList: [],
    });

    const handleChooseMemberSuccess = (detail) => {
      state.showMemberList = detail.user.map((item) => ({
        uid: item.uid,
        realname: item.realname,
        avatar: item.avatar,
      }));
      state.memberCheckedList.user = detail.user.map((item) => item.uid);
      state.chooseMemberVisible = false;
    };

    const memberRemove = (index) => {
      state.showMemberList.splice(index, 1);
      state.memberCheckedList.user.splice(index, 1);
    };

    // 是否是发起、结束流程
    const isStartOrEnd = computed(() => {
      return state.process.type == "start" || state.process.type == "end";
    });

    // 是否全部可读
    const readAllChange = () => {
      state.controlList.forEach((item) => {
        item.read = state.readAll;
      });
    };
    // 是否所有可读(true)/不可读(false)
    const isAllRead = (condition = true) => {
      for (let item of state.controlList) {
        if (
          (condition == true && !item.read) ||
          (condition == false && item.read)
        ) {
          return false;
        }
      }
      return true;
    };
    // 是否可读
    const readChange = (read) => {
      state.readAll = read ? isAllRead() : false;
    };

    const getListFromData = (type) => {
      const { data } = state.process;
      if (type == "copy") {
        return data.ccList;
      }
      if (type == "approval") {
        return data.approver;
      }
      if (type == "deal") {
        return data.dealer;
      }
    };

    // 添加操作人
    let count = 0;
    const addHandlerItem = (type) => {
      count++;
      const newItem = { ...common.defaultMemberCard };
      newItem.key = type + "_" + count;
      const list = getListFromData(type);
      list.push(newItem);
    };

    // 移除操作人
    const removeHandlerItem = (e) => {
      const { info, type } = e;
      const list = getListFromData(type);
      const index = list.findIndex((item) => item.key == info.key);
      if (index > -1) {
        list.splice(index, 1);
      }
    };

    // 取消
    const onClose = () => {
      emit("cancel");
    };

    // 保存
    const onSubmit = () => {
      if (isAllRead(false)) {
        state.process.error = "请至少设置一个控件可读";
        // return;
      } else {
        let { type, data, dealerTxt, error } = state.process;
        state.process.error = "";
        state.process.dealerTxt = [];
        // 可读控件
        data.controlsRead = [];
        state.controlList.forEach((item) => {
          if (item.read) {
            data.controlsRead.push(item.key);
          }
        });
        // 处理人、审批人为空时
        if (
          (type == "approval" && data.approverEmpty == 2) ||
          (type == "deal" && data.dealerEmpty == 2)
        ) {
          if (state.memberCheckedList.user.length) {
            data.emptyMember = state.memberCheckedList.user;
            data.emptyMemberDetail = state.showMemberList;
          } else {
            state.process.error = `${
              type == "approval" ? "审批" : "办理"
            }人为空时未指定人员`;
          }
        }
        if (
          ((type == "approval" && data.approverEmpty == 3) ||
            (type == "deal" && data.dealerEmpty == 3)) &&
          !data.emptyAdmin
        ) {
          state.process.error = `${
            type == "approval" ? "审批" : "办理"
          }人为空时转交给审批管理员未选择审批管理员`;
        }
        // 处理外部显示文字
        if (type == "approval") {
          if (data.approver && data.approver.length) {
            let txtArr = data.approver.map((item) => {
              if (item.type == 3 && !item.memberList.length) {
                state.process.error = "未设置审批人";
              }
              return common.dealerType.find((item2) => item2.value == item.type)
                .label;
            });
            txtArr = Array.from(new Set(txtArr));
            state.process.dealerTxt.push(`审批人：${txtArr.join("，")}`);
          } else {
            state.process.error = "未设置审批人";
          }
        }
        if (type == "deal") {
          if (data.dealer && data.dealer.length) {
            let txtArr = data.dealer.map((item) => {
              if (item.type == 3 && !item.memberList.length) {
                state.process.error = "未设置处理人";
              }
              return common.dealerType.find((item2) => item2.value == item.type)
                .label;
            });
            txtArr = Array.from(new Set(txtArr));
            state.process.dealerTxt.push(`处理人：${txtArr.join("，")}`);
          } else {
            state.process.error = "未设置处理人";
          }
        }
        if (data.ccList && data.ccList.length) {
          let txtArr = data.ccList.map((item) => {
            if (item.type == 3 && !item.memberList.length) {
              state.process.error = "未设置抄送人";
            }
            return common.dealerType.find((item2) => item2.value == item.type)
              .label;
          });
          txtArr = Array.from(new Set(txtArr));
          state.process.dealerTxt.push(`抄送人：${txtArr.join("，")}`);
        }
      }
      if (props.fromOther) {
        delete state.process.data.controlsRead;
      }
      emit("finish", state.process);
    };
    const formColumns = ref([]);

    // 初始化
    const init = () => {
      formColumns.value.push({
        title: "表单字段",
        key: "name",
        dataIndex: "name",
      });

      if (!props.fromOther) {
        formColumns.value.push({
          key: "readCol",
          dataIndex: "key",
        });
      }
      state.process = JSON.parse(JSON.stringify(props.content));
      console.log("--------------------process", toRaw(state.process));
      state.memberCheckedList.user = state.process.data.emptyMember || [];
      state.showMemberList = state.process.data.emptyMemberDetail || [];
      state.controlList = store.getters.approvalFormDesign.map((item) => {
        let newItem = {
          key: item.key,
          read: true,
        };

        //删除 state.lastControlKeys.includes(item.key) && 上一次没有勾选不可读的保持不可读
        if (
          state.process.data.controlsRead &&
          state.process.data.controlsRead.length &&
          !state.process.data.controlsRead.includes(item.key)
        ) {
          // 按接口返回的数据去处理 勾选
          newItem.read = false;
        }
        if (item.type == "daterange") {
          newItem.name =
            item.setting.name[0] && item.setting.name[1]
              ? `${item.setting.name[0]}-${item.setting.name[1]}`
              : item.title;
        } else if (item.type == "tips") {
          newItem.name = item.setting.placeholder || item.title;
        } else {
          newItem.name = item.setting.name || item.title;
        }
        return newItem;
      });
      state.isAllRead = isAllRead();
      state.readAll = isAllRead();
    };

    // 重置
    const reset = () => {
      state.lastControlKeys = state.controlList.map((item) => item.key);
      state.controlList = [];
      state.settingType = 1;
      state.process = {};
      state.memberCheckedList.user = [];
      state.showMemberList = [];
      formColumns.value = [];
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          reset();
        }
      }
    );

    return {
      isStartOrEnd,
      formColumns,
      common,
      radioStyle: {
        display: "block",
        height: "30px",
        lineHeight: "30px",
      },
      ...toRefs(state),
      onClose,
      onSubmit,
      readAllChange,
      readChange,
      addHandlerItem,
      removeHandlerItem,
      handleChooseMemberSuccess,
      memberRemove,
    };
  },
});
</script>

<style lang="less" scoped>
.content {
  height: 100%;
  overflow: hidden auto;
  .module {
    margin-bottom: 20px;
    .text-title2 {
      font-weight: bold;
      color: rgba(0, 0, 0, 0.7);
      line-height: 40px;
      // padding-left: 4px;
    }
  }
}
.user-tag {
  :deep(.ant-tag) {
    border-radius: 20px !important;
    padding: 0 12px 0 0 !important;
    background: #f1f1f1;
    border: none;
  }
}
</style>
